package helper

import (
	"crypto/tls"
	"fmt"
	"math/rand"
	"net/smtp"
	"time"

	"github.com/jordan-wright/email"
	"github.com/zeromicro/go-zero/core/logx"
)



func RandCode() string {
	s := "1234567890"

	code := ""

	rand.Seed(time.Now().UnixNano())
	for i := 0; i < int(c.Email.CodeLength); i++ {
		code += string(s[rand.Intn(len(s))])
	}
	return code
}

func SendEmail(mail, code string) error {
	e := email.NewEmail()

	e.From = c.Email.From
	e.To = []string{mail}
	e.Subject = c.Email.Subject
	e.HTML = []byte(`
	<!DOCTYPE html>
	<html lang="en">
	<head>
	    <meta charset="UTF-8">
	    <title>Verification Code</title>
	</head>
	<body>
	    <h1>Cloud Disk | 你的验证码为: ` + code + `</h1>
	</body>
	</html>
	`)

	// 设置 TLS 配置
	tlsConfig := &tls.Config{
		InsecureSkipVerify: true,
		ServerName:         c.Email.Smtp,
	}

	// 构造 SMTP 服务器地址
	smtpAddr := fmt.Sprintf("%s:%d", c.Email.Smtp, c.Email.SmtpPort)

	// 发送邮件
	err := e.SendWithTLS(smtpAddr, smtp.PlainAuth("", c.Email.From, c.Email.Password, c.Email.Smtp), tlsConfig)
	if err != nil {
		logx.Error("Failed to send email", logx.Field("error", err))
		// bug 不返回错误，继续执行后续逻辑
		return nil
	}

	return nil
}
